module.exports = core;
const pkg = require('../package.json');
const constant= require('./const')
const commander = require('commander')

const log = require('@imooc-cli-dev/log');
const exec = require('@imooc-cli-dev/exec')

// user-home 弃用了
const { homedir } = require('os')
const pathExistsSync = require('path-exists').sync;
const semver = require('semver');
const path = require('path');
const colors = require('colors/safe');

const program = new commander.Command();

const { getOnLineLatestVersion } = require('@imooc-cli-dev/get-npm-info')

let userHome = undefined;
let args = [];

async function core(args) {
  // try {
    await prepare()
    registCommander()
  // } catch (error) {
  //   log.error(error.message)
  // }
}

// 注册命令
function registCommander() {
  program
    .name(Object.keys(pkg.bin)[0])
    .version(pkg.version, '-v, -V', '--version', '显示版本号')
    .option('-tp, --targetPath <targetPath>', '是否指定本地调试文件路径' )
    .option('-d, --debug', '开启debugger模式', false)
    .usage('<command> [option]')

  program.on('option:debug', () => {
    const args = program.opts();
    if(args.debug) {
      process.env.LOG_LEVEL = 'verbose';
    } else {
      process.env.LOG_LEVEL = 'info'
    }
    log.level = process.env.LOG_LEVEL;
    log.verbose('debug', 'debug start')
  })

  // 监听未匹配到的command
  program.on('command:*', (obj) => {
    const availableCommands = program.commands.map((cmd) => cmd.name());
    console.log(colors.red(`未知的命令：${obj[0]}`))
    if( availableCommands.length > 0 ) {
      console.log(colors.green(`可用命令：${availableCommands.join(',')}`))
    }
  })

  program
    .command('init [projectName]')
    .description('初始化项目')
    .option('-f, --force', '强制初始化')
    .action(exec)

  program.on('option:targetPath', function(obj) {
    const tagArgs = program.opts()
    // 这里使用全局的cli进行传递参数
    process.env.CLI_TARGET_PATH = tagArgs.targetPath;
  })
  if(args._.length < 1) {
    program.outputHelp()
  } else {
    program.parse()
  }

}

async function prepare() {
  // 检查包版本号
  checkPkgVersion()
  // 检查node版本
  // checkNodeVersion()
  // 检查root启动,如果是就降级
  checkRoot()
  // 检查用户主目录，需要在检查入参数钱，我们可能会用log.verbose;
  checkUserHome()
  // 检查入参 
  checkInputArgs()
  // 检查环境变量
  checkEnv()
  // 检查是否为最新版本
  // 提示更新
  await checkGlobalUpdate()
}

function checkInputArgs() {
  const minimist = require('minimist');
  args = minimist(process.argv.slice(2));
  // checkArgs()
  // minimist 解析参数
  // console.log(process.argv.slice(2), 'process.argv.slice(2)')
  // [ 'init', 'name', '-d', '--abcv=123' ] process.argv.slice(2)
  // console.log( args, 'args')
  // { _: [ 'init', 'name' ], d: true, abcv: 123 } args
}

function checkArgs() {
  if(args.debug) {
    process.env.LOG_LEVEL = 'verbose';
  } else {
    process.env.LOG_LEVEL = 'info'
  }
  log.level = process.env.LOG_LEVEL;
  log.verbose('debug', 'debug start')
}

function checkNodeVersion() {
  // 获取当前node版本
  const currentVersion = process.version;
  const lowestVersion = constant.LOWEST_NODE_VERSION;
  if(semver.lt(currentVersion, lowestVersion)) {
    throw new Error(colors.red('请升级node版本至' + lowestVersion))
  }
}

async function checkGlobalUpdate() {
  const currentVersion = pkg.version;
  const pkgName = pkg.name;
  // 获取最新的小版本
  const lastVersion = await getOnLineLatestVersion(currentVersion,pkgName)
  if(lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn(
      'update',
      colors.yellow(
        [
          `请手动更新 ${pkgName}，当前版本：${currentVersion}，最新版本：${lastVersion}`,
          `更新命令 npm install ${pkgName}`
        ].join('\n')
      )
    );
  }
}

function checkEnv() {
  const dotenv = require('dotenv');
  // 这边这个imooc-env有点迷，是需要用户去手动新建一个吗。。感觉有点问题
  const dorenvPath = path.resolve(userHome, '.env');
  let config;
  // 用户不新建，则这边一直都是false
  if(pathExistsSync(dorenvPath)) {
    // path 默认是 process.pwd() + '.env
   dotenv.config({ path: dorenvPath }).parsed;
  } else {
   createDefaultConfig()
  }
}

function createDefaultConfig() {
  const cliHome = path.join(
    userHome,
    process.env.CLI_HOME_PATH || constant.DEFAULT_CLI_HOME
  )
  process.env.CLI_HOME_PATH = cliHome;
}

function checkUserHome() {
  userHome = homedir();

  if (!userHome || !pathExistsSync(userHome)) {
    throw new Error(colors.red('当前用户主目录不存在！'));
  }
}

function  checkRoot () {
  // console.log(process.geteuid())
  // 通过sudo启动 值为0
  const rootChheck = require('root-check');
  rootChheck()
  // 通过sudo启动 值为501
  // console.log(process.geteuid())
}

function checkPkgVersion() {
  const version = pkg.version;
  log.success('cli', `checked version ${version}`);
}